package m.member.order.action;

import com.alibaba.fastjson.JSONObject;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.Text;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.member.manage.action.MemberInfoAction;
import m.member.manage.model.MemberInfo;
import m.member.manage.model.MemberLevel;
import m.member.manage.service.AppSettingService;
import m.member.order.model.OrderDetail;
import m.member.order.model.OrderInfo;
import m.member.order.service.OrderInfoService;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import manage.action.ManageAction;
import manage.model.OrgGroupView;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "member/order/orderInfo")
public class OrderInfoAction extends ManageAction {
    private OrderInfo model;
    private List<JSONObject> list;
    public JSONMessage doSave() throws Exception {
        verifyAdminOperPower("order_input_power");
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        model.setInputDate(new Date());
        String msg=getService(OrderInfoService.class).save(model,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg",msg)
                .push("model",model);
    }
    public JSONMessage doSaveAll() throws Exception {
        verifyAdminOperPower("order_input_power");
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        model.setInputDate(new Date());
        String msg=getService(OrderInfoService.class).saveAll(model,list,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg",msg)
                .push("model",model);
    }
    public JSONMessage doSubmitAll() throws Exception {
        doSaveAll();//先保存再提交
        getService(OrderInfoService.class).submit(model,getSessionAdmin());
        return new JSONMessage(0)
                .push("msg","提交成功");
    }
    public JSONMessage doDelete() throws Exception {
        verifyAdminOperPower("order_input_power");
        getService(OrderInfoService.class).delete(model,getSessionAdmin());
        return new JSONMessage(0)
                .push("msg","删除成功");
    }
    public JSONMessage doSubmit() throws Exception {
        verifyAdminOperPower("order_input_power");
        getService(OrderInfoService.class).submit(model,getSessionAdmin());
        return new JSONMessage(0)
                .push("msg","提交成功");
    }
    public JSONMessage doBack() throws Exception {
        verifyAdminOperPower("order_confirm_power");
        getService(OrderInfoService.class).back(model);
        return new JSONMessage(0)
                .push("msg","退回成功");
    }
    public JSONMessage doConfirm() throws Exception {
        verifyAdminOperPower("order_confirm_power");
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        getService(OrderInfoService.class).confirm(model,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg","确认成功");
    }
    public JSONMessage getInfo() throws Exception {
        verifyAdminOperPower("recharge_input_power");
        if(ObjectUtil.isEmptyOid(model)){
            OrgGroupView org=getSessionOrgGroup();
            if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
                throw new MException(this.getClass(),"无店铺信息");
            model=new OrderInfo();
            model.setPayType("0");
            model.setOtherAmount(0d);
            model.setInputDate(new Date());
            model.setInputAdmin(getSessionAdmin());
            model.setServeAdmin(getSessionAdmin());
            model.setInputDept(org.getDept());
        }else {
            model = ModelQueryList.getModel(model, "*", "member.*", "member.level.*", "serveAdmin.*", "inputAdmin.*", "inputDept.*");
            String pn = model.getMember().getPhoneNum();
            model.getMember().setPhoneNum(pn.substring(0, 3) + "****" + pn.substring(pn.length() - 4));
        }
        return new JSONMessage(0)
                .push("model",model)
                .push("confirmPower",hasAdminOperPower("recharge_confirm_power"));
    }

    public JSONMessage getInfoAll() throws Exception {
        if(ObjectUtil.isEmptyOid(model)){
            verifyAdminOperPower("recharge_input_power");
            OrgGroupView org=getSessionOrgGroup();
            if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
                throw new MException(this.getClass(),"无店铺信息");
            model=new OrderInfo();
            model.setOrderAmount(0d);
            model.setPayType("0");
            model.setOtherAmount(0d);
            model.setInputDate(new Date());
            model.setInputAdmin(getSessionAdmin());
            model.setServeAdmin(getSessionAdmin());
            model.setInputDept(org.getDept());
        }else {
            model = ModelQueryList.getModel(model, "*", "member.*", "member.level.*", "serveAdmin.*", "inputAdmin.*", "inputDept.*");
            String pn = model.getMember().getPhoneNum();
            model.getMember().setPhoneNum(pn.substring(0, 3) + "****" + pn.substring(pn.length() - 4));
        }
        int dayRate=getService(AppSettingService.class).getDiscount(model.getInputDate());
        List<OrderDetail> list=ModelQueryList.getModelList(OrderDetail.class,new String[]{"*","serve.*","serve.type.*"},null,
                QueryCondition.eq("order.oid",model.getOid()), QueryOrder.asc("oid"));
        return new JSONMessage(0)
            .push("dayRate",dayRate)
            .push("model",model)
            .push("list",list);
    }
    /**
     * 编辑页面
     */
    @RequestMeta(params = {"edit"})
    public VueResult toOrderInfo(boolean edit) throws Exception {
        verifyAdminOperPower("recharge_input_power");
        ModelForm form=new ModelForm("会员订单",3);
        form.addItem(
            FormInput.selectOneModel("会员信息","model","member","'"+actionUrl(MemberInfoAction.class,"selectList")+"'",750,
                Element.tag("template").A("v-if","model.member.oid")
                .E(Element.tag("a-tag").A(":color","model.member.level.color").E("{{model.member.level.name}}"))
                .E(Element.tag("a-tag").A("color","success").A("v-if","model.member.level.discount").E("优惠{{model.member.level.discount}}%"))
                .E("{{model.member.realName}} {{model.member.phoneNum}}")
                .E(" <small>余额</small><span class=\"text-red\">{{formatNumber(model.member.balance-model.member.freeze,'#,##0.00')}}</span><small>元</small>")
                .toString()
            ).setEdit(edit).setSpan(2),
            FormTest.test("confirmPower",FormInput.selectOneAdmin("服务员","model","serveAdmin","model.inputDept.oid","","{{model.serveAdmin.realname}}").setEdit(edit))
                    .other(FormHtml.ins("服务员","{{model.serveAdmin.realname}}")),
            FormInput.radio("付款方式","model.payType","m.member.order.model.OrderInfo!payType").setEdit(edit).setSpan(3),
            FormHtml.ins("订单金额","<span class=\"text-red text-lg\">{{formatNumber(model.orderAmount,'#,##0.00')}}</span>元"),
            FormInput.number("其他金额","model.otherAmount","元","#,##0.00",2).setEdit(edit).setPlaceholder("请输入其他金额").setDescription("若该订单有其他优惠(填负数)或补差价(填正数)，请在处填写。"),
            FormHtml.ins("实付金额","<span class=\"text-red text-lg\">{{formatNumber(model.payAmount,'#,##0.00')}}</span>元"),
            FormHtml.ins("优惠合计","会员优惠 <span class=\"text-red text-lg\">{{formatNumber(model.preferentialAmount,'#,##0.00')}}</span>元"
                +"<span v-if=\"model.memberDayAmount\" class=\"padding-left\">会员日 <span class=\"text-red text-lg\">{{formatNumber(model.memberDayAmount,'#,##0.00')}}</span>元</span>")
                .setSpanVal("lackMoney>0&&model.payType=='0'?2:3"),
            FormTest.test("lackMoney>0&&model.payType=='0'",FormInput.checkBoxGroup("差<span class=\"text-red text-lg\">{{lackMoney}}</span>元","model.payOper","m.member.order.model.OrderInfo!payOper").setEdit(edit)),
            FormInput.textarea("备注","model.remark").setEdit(edit).setPlaceholder("请输入备注").setSpan(3),
            FormHtml.ins("录入人","{{model.inputAdmin.realname}}"),
            FormHtml.ins("录入店铺","{{model.inputDept.name}}"),
            FormHtml.ins("录入时间","{{formatDate(model.inputDate,'yyyy-MM-dd')}}")
        )
        .addData("dayRate",0)//会员日优惠比例
        .addData("lackMoney",0)
        .addData("model", null!=model?model:new OrderInfo())
        .addData("confirmPower",hasAdminOperPower("recharge_confirm_power"))
        .addButton(
            FormButton.pri("保存","doSaveAll").setTest(String.valueOf(edit)).setDisabled("editRecord"),//editRecord是TableForm正在编辑的对象，存在则禁用按钮
            FormButton.succ("提交","doSubmitAll").setTest(String.valueOf(edit)).setDisabled("editRecord").setConfirm("确定要提交吗？")
        )
        .addWatch("model.member.oid","this.setOrderAmount(this.model.orderAmount);")
        .addWatch("model.otherAmount","this.setOrderAmount(this.model.orderAmount);")
        .addWatch("model.payType","this.setOrderAmount(this.model.orderAmount);")
        .setMounted("this.getInfoAll();")//页面初始化加载信息
        .addMethod(
            FormEvent.backFlag,
            FormEvent.verify("verifyModel",
                FormJsTest.falseRemind("this.model.member.oid","请选择会员信息"),
                FormJsTest.falseRemind("this.model.serveAdmin.oid","请选择服务员"),
                FormJsTest.falseRemind("this.list.length>0","请添加服务明细")
            ),
            FormEvent.doJson("getInfoAll",actionUrl("getInfoAll"),"{model:this.model}")
                .fillData("model","dayRate","list"),
            FormEvent.doJson("doSaveAll",actionUrl("doSaveAll"),"{model:this.model,list:this.list}")
                .before("verifyModel").fillData("model").after("getInfoAll"),
            FormEvent.doJson("doSubmitAll",actionUrl("doSubmitAll"),"{model:this.model,list:this.list}")
                .before("verifyModel").success("backFlag"),
            FormEvent.custom("setOrderAmount(amount)",//设置金额
                "this.model.orderAmount=amount;" +
                "this.model.preferentialAmount=this.roundNumber(amount*this.model.member.level.discount/100,2);" +
                "this.model.memberDayAmount=-this.roundNumber((amount-this.model.preferentialAmount+this.model.otherAmount)*this.dayRate/100,2);" +
                "this.model.payAmount=this.roundNumber(amount-this.model.preferentialAmount+this.model.otherAmount+this.model.memberDayAmount,2);" +
                "if(this.model.payType=='0') this.lackMoney=this.roundNumber(this.model.payAmount-(this.model.member.balance-this.model.member.freeze),2);" +
                "else this.lackMoney=0;" +
                "if(this.lackMoney<=0) this.model.payOper='';"
            )
        );
        //table表单
        TableForm table=new TableForm("服务明细").setEdit(edit,true,"{serve:{type:{}},num:1}");
        table.addColumn(
            TableColumn.text("类型","serve.type.name")
            .setShow(Element.tag("a-tag").A(":color","record.serve.type.color").E("{{record.serve.type.name}}"))
            .setEdit(Element.tag("a-tag").A(":color","editRecord.serve.type.color").E("{{editRecord.serve.type.name}}")),
            TableColumn.text("服务","serve.title")
            .setEdit(TableEdit.selectOneModel("'action/member/manage/serveGoods/selectList'",750,"serve","title")),
            TableColumn.text("描述","serve.description",150)
            .setEdit(new Text("{{editRecord.serve.description}}")),
            TableColumn.number("单价","price").isSum(false)
            .setShow(new Text("{{record.price}}"))
            .setEdit(new Text("{{editRecord.serve.price}}")),
            TableColumn.number("优惠","discount").isSum(false)
            .setShow(Element.tag("a-tag").A("color","processing").E("{{record.discount}}%").A("v-if","record.discount"))
            .setEdit(Element.tag("a-tag").A("color","processing").E("{{editRecord.serve.discount}}%").A("v-if","editRecord.serve.discount")),
            TableColumn.number("数量","num").setNumberFormat("#,##0")
            .setEdit(TableEdit.number("","#,##0",0)),
            TableColumn.number("金额","total")
            .setEdit(new Text("{{editRecord.serve.oid?roundNumber(editRecord.serve.price*editRecord.num*(100-editRecord.serve.discount)/100,2):0}}"))
        )
        .setData("list",new ArrayList<>())
        .addMethod(
            FormEvent.custom("editDone(record)",//编辑行完成
                "record.price=record.serve.price;" +
                "record.discount=record.serve.discount;" +
                "record.total=this.roundNumber(record.serve.price*record.num*(100-record.serve.discount)/100,2);"
            ),
            FormEvent.custom("rowChangeHandler",//合计金额设置订单金额 sumDataRow是TableForm内置方法,deleteFlag是存在oid时删除的标识
                "this.setOrderAmount(this.sumDataRow(item=>item.deleteFlag?0:item.total));"
            )
        )
        .setEditRowConfirm("editDone")
        .setRowChangeAfter("rowChangeHandler");
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(table);
    }
    /*
     * 订单列表
     */
    public VueResult allList() throws Exception {
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        String menu=getParamsValue("menu");
        VueListResult result=getVueListResult("会员订单列表", OrderInfo.class,"action/member/order/orderInfo/allList");
        result.setFunction(true,false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addQueryFields("member.level.color","member.level.name","status");
        result.addCol(toTextColumn("会员级别", "member.level.oid", 100, true)
            .addElement(new ListElement("a-tag")
                .addAttr(":color","record.member.level.color")
                .addText("{{record.member.level.name}}")
            )
            .setDictType(MemberLevel.class)
            .setAlign(Align.CENTER)
        );
        result.addCol(toLinkColumn("会员", "member.realName", 100, true,
            new ListEvent(actionUrl(MemberInfoAction.class,"toView"),EventType.MODAL,1000)
                .addParam("model.oid","member.oid")
        ));
        result.addCol(toTextColumn("服务员", "serveAdmin.realname", 100, true));
        result.addCol(toNumberColumn("明细合计", "orderAmount", 100, true)
            .setType(ListColumnType.LINK)
            .setLinkEvent(new ListEvent(actionUrl(OrderDetailAction.class,"subList"),EventType.MODAL,1100)
                .addParam("params[order.oid]","oid"))
        );
        result.addCol(toNumberColumn("优惠金额", "preferentialAmount", 100, true));
        result.addCol(toNumberColumn("其他金额", "otherAmount", 100, true));
        result.addCol(toNumberColumn("会员日", "memberDayAmount", 100, true));
        result.addCol(toTextColumn("付款类型","payType",100,true).setDictType("m.member.order.model.OrderInfo!payType")
            .addElement(new ListElement("a-tag")
                .addAttr(":color","decode(text,'0','#389e0d','A','processing','B','success','C','error','D','warning','default')")
                .addText("{{dict('m.member.order.model.OrderInfo!payType',text)}}")
            )
            .setAlign(Align.CENTER)
        );
        result.addCol(toNumberColumn("实付金额", "payAmount", 100, true)
            .setType(ListColumnType.LINK)
//            .setLinkEvent(new ListEvent("page/member/order/viewOrderInfo.js",EventType.MODAL,1100)
//                .addParam("oid","oid")
            .setLinkEvent(new ListEvent(actionUrl("toOrderInfo")+"?edit=false",EventType.MODAL,1100)
                .addParam("model.oid","oid")

        ));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toDateColumn("录入时间", "inputDate", 100, true));
        result.addSearch(ListSearch.custom("菜单类型","menu", SearchType.HIDDEN_EQ));
        //菜单区分
        if(!"input".equals(menu)) {
            result.addCol(toTextColumn("录入人", "inputAdmin.realname", 100, true));
        }
        if("done".equals(menu)) {
            result.addCol(toTextColumn("店铺", "inputDept.name", 100, true));
            result.addCol(toTextColumn("确认人", "confirmAdmin.realname", 100, true));
            result.addCol(toDateColumn("确认时间", "confirmDate", 100, true));
        }
        if("input".equals(menu)&&hasAdminOperPower("order_input_power")){
            result.addCondition(QueryCondition.eq("inputAdmin.oid",getSessionAdminOid()));
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.in("status","A","N"));
            result.addCol(toSpaceColumn("操作", 130,
//                ListElement.test("record.status=='A'",
//                    ListButton.modal("修改", ButtonType.PRIMARY, "page/member/order/editOrderInfo.js", 1100, SuccessMethod.MUST_REFRESH)
//                        .addParam("oid", "oid")
//                ),
                ListElement.test("record.status=='A'",
                    ListButton.modal("修改", ButtonType.PRIMARY, actionUrl("toOrderInfo")+"?edit=true", 1100, SuccessMethod.MUST_REFRESH)
                        .addParam("model.oid", "oid")
                ),
                ListElement.test("record.status=='A'",
                    ListButton.ajax("删除", ButtonType.ERROR, actionUrl("doDelete"), SuccessMethod.REFRESH)
                        .addParam("model.oid", "oid").setConfirm("确定要删除吗？")
                )
            ).setFixed(Align.RIGHT));
//            result.addButton(ListButton.modal("新增", ButtonType.PRIMARY, "page/member/order/editOrderInfo.js", 1100, SuccessMethod.MUST_REFRESH));
            result.addButton(ListButton.modal("新增", ButtonType.PRIMARY, actionUrl("toOrderInfo")+"?edit=true", 1100, SuccessMethod.MUST_REFRESH));
        }else if("confirm".equals(menu)&&hasAdminOperPower("order_confirm_power")){
            result.setSubTitle("请及时确认订单");
            result.setSelection("oid",false);
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.eq("status","N"));
            result.addCol(toSpaceColumn("操作", 130,
                ListButton.ajax("确认", ButtonType.PRIMARY, actionUrl("doConfirm"), SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid").setConfirm("确认后生效且不可修改，该记录已核实了吗？"),
                ListButton.ajax("退回", ButtonType.ERROR, actionUrl("doBack"), SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid").setConfirm("确定要退回订单吗？")
            ).setFixed(Align.RIGHT));
            result.addButton(ListButton.ajax("批量确认", ButtonType.PRIMARY, actionUrl("doConfirm"), SuccessMethod.REFRESH)
                .addParam("model.oid", "oid").setConfirm("确认后生效且不可修改，该记录已核实了吗？"));
        }else if("done".equals(menu)){
            if(!hasAdminOperPower("order_confirm_power")) {
                result.setSubTitle("我负责的已完成订单");
                result.addCondition(QueryCondition.eq("inputAdmin.oid", getSessionAdminOid()));
            }else{
                result.setSubTitle("店铺的已完成订单");
            }
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.eq("status","Y"));
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }

    /*
     * 会员订单列表
     */
    public VueResult memberOrderList() throws Exception {
        VueListResult result=getVueListResult("订单列表", OrderInfo.class,actionUrl("memberOrderList"));
        result.setFunction(true,false);
        result.hideHead();
        result.setPageSize(10);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("店铺", "inputDept.name", 100, true));
        result.addCol(toTextColumn("服务员", "serveAdmin.realname", 100, true));
        result.addCol(toDateColumn("录入时间", "inputDate", 100, true));
        result.addCol(toTextColumn("状态","status",80,true).setDictType("m.member.order.model.OrderInfo!status").setAlign(Align.CENTER));
        result.addCol(toNumberColumn("明细合计", "orderAmount", 100, true)
            .setType(ListColumnType.LINK)
            .setLinkEvent(new ListEvent(actionUrl(OrderDetailAction.class,"subList"),EventType.MODAL,1000)
                .addParam("params[order.oid]","oid"))
        );
        result.addCol(toNumberColumn("优惠金额", "preferentialAmount", 100, true));
        result.addCol(toNumberColumn("其他金额", "otherAmount", 100, true));
        result.addCol(toNumberColumn("会员日", "memberDayAmount", 100, true));
        result.addCol(toTextColumn("付款类型","payType",100,true).setDictType("m.member.order.model.OrderInfo!payType")
            .addElement(new ListElement("a-tag")
                .addAttr(":color","decode(text,'0','#389e0d','A','processing','B','success','C','error','D','warning','default')")
                .addText("{{dict('m.member.order.model.OrderInfo!payType',text)}}")
            )
            .setAlign(Align.CENTER)
        );
        result.addCol(toNumberColumn("实付金额", "payAmount", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toTextColumn("录入人", "inputAdmin.realname", 100, true));
        result.addSearch(ListSearch.field("会员oid","member.oid",SearchType.HIDDEN_EQ));
        return result;
    }
    public OrderInfo getModel() {
        return model;
    }

    public void setModel(OrderInfo model) {
        this.model = model;
    }

    public List<JSONObject> getList() {
        return list;
    }

    public void setList(List<JSONObject> list) {
        this.list = list;
    }
}
